<?php
// $Id$

/**
 * @file
 * nexlistforms.php
 */

/* the following is for the add-form */
function nexlist_form_add() {
  $form['name'] = array(
    '#type'           => 'textfield',
    '#title'          => 'Name',
    '#size'           => 20,
    '#default_value'  => '',
    '#maxlength'      => 255,
    //'#description'    => 'Name of the new list',
    '#required'       => TRUE,
  );

  $form['description'] = array(
    '#type'           => 'textfield',
    '#title'          => 'Description',
    '#size'           => 20,
    '#default_value'  => '',
    '#maxlength'      => 255,
    //'#description'    => 'Description',
    '#required'       => TRUE,
  );

  $form['numberofitems'] = array(
    '#type'           => 'textfield',
    '#title'          => 'Number of Fields',
    '#default_value'  => '1',
    '#maxlength'      => 3,
    '#size'           => 3,
    //'#description'    => 'Number of Fields',
    '#required'       => TRUE,
  );

  $form['submit'] = array(
    '#type'           => 'submit',
    '#value'          => 'Save',
    //'#submit'         => 'nexlist_add_form_submit',
  );

  $form['#submit'][] = 'nexlist_add_form_submit';

  return $form;
}

function nexlist_add_form_submit($form, &$form_state) {
  $name = ($form_state['values']['name']);
  $desc = ($form_state['values']['description']);

  db_query("INSERT INTO {nexlist} (module, name, description, active) VALUES ('all', '%s', '%s', 1)", $name, $desc);
  $id = db_last_insert_id('nexlist', 'id');

  //ok, now lets insert some blanks into the fields table to house the items in for editing...
  for ($cntr = 0; $cntr < $form_state['values']['numberofitems']; $cntr++) {
    db_query("INSERT INTO {nexlist_fields} (lid, fieldname) VALUES (%d, 'Field %d')", $id, $cntr);
  }

  drupal_goto('admin/settings/nexlist/edit/' . $id);
}

function nexlist_theme_form_add($form) {
  //ok, so we have to now lay out the form in the template
  $output = theme("nexlist_form_add_elements", $form);
  return $output ;
}

function template_preprocess_nexlist_form_add_elements(&$vars) {
  global $user;
}

/* end add form area */


/* the following is for the add-form-fields */
function nexlist_form_add_fields($form_state, $nexlist_id=0) {
  //what we have to do here is create the display
  //so that there is a dynamically allocated number of form elements and their associated values.
  $sql = "SELECT id,fieldname,value_by_function,predefined_function from {nexlist_fields} WHERE lid=%d";
  $res = db_query($sql, $nexlist_id);
  $cnt = db_affected_rows();

  //we'll loop thru $cnt to create $cnt number of form entry fields and their values
  //lets generate the list of custom functions:
  $array_of_functions = nexlist_get_custom_list_functions();

  for ($cntr = 0; $cntr < $cnt; $cntr++) {
    $A = db_fetch_array($res);

    $form['removefield' . $cntr] = array(
      '#type'           => 'submit',
      '#value'          => 'X',
      '#attributes'     => array('onClick' => "document.getElementById('edit-delid').value='{$A['id']}';"),
    );

    $form['id' . $cntr] = array(
      '#value'          => $A['id'],
      '#type'           => 'hidden',
      '#required'       => TRUE,
    );

    $form['name' . $cntr] = array(
      '#value'          => $A['fieldname'],
      '#type'           => 'textfield',
      '#size'           => 20,
      '#default_value'  => '',
      '#maxlength'      => 255,
      '#required'       => TRUE,
    );

    $displayarray = array();
    $defaultvalue = '';
    $listvalues = '';
    if ($A['predefined_function'] == 1) {
      $displayarray['Static Value'] = 'Static Value';
      $displayarray[$A['value_by_function']] = $A['value_by_function'];

      if (drupal_strpos($A['value_by_function'], '[list:') !== FALSE) {
        $defaultvalue = 'nexlistGetOtherList';
        $listvaluesstr = drupal_substr($A['value_by_function'], 6);
        $listvaluesstr = str_replace(']', '', $listvaluesstr);
        $listvalues = explode(',', $listvaluesstr);
      }
      else {
        $defaultvalue = $A['value_by_function'];
      }
    }
    else {
      $displayarray=array('Static Value' => 'Static Value');
      $defaultvalue = 'Static Value';
    }

    $displayarray = array_merge($displayarray, $array_of_functions);
    $form['fnvalue' . $cntr] = array(
      '#type'           => 'select',
      '#options'        => $displayarray,
      '#size'           => 1,
      '#default_value'  => $defaultvalue,
      '#maxlength'      => 255,
      '#required'       => FALSE,
      '#attributes'     => array('onChange' => "hide_applicable_fields(this.value, '$cntr');")
    );

    $form['value' . $cntr] = array(
      '#type'           => 'textfield',
      '#value'          => $A['value_by_function'],
      '#size'           => 20,
      '#default_value'  => $A['value_by_function'],
      '#maxlength'      => 255,
      '#required'       => TRUE,
    );

    $listres = db_query("SELECT id, name FROM {nexlist}");
    $listoptions = array(0 => 'Select List');
    while ($listret = db_fetch_array($listres)) {
      $listoptions[$listret['id']] = $listret['name'];
    }

    $form['list' . $cntr] = array(
      '#type'           => 'select',
      '#options'        => $listoptions,
      '#size'           => 1,
      '#default_value'  => (is_array($listvalues)) ? $listvalues[0]:'',
      '#maxlength'      => 255,
      '#required'       => FALSE,
      '#ahah'           => array(
        'path'            => 'admin/settings/nexlist/getfields/' . $cntr,
        'wrapper'         => 'replace_fields' . $cntr,
        'method'          => 'replace',
        'effect'          => 'fade'
      ),
      '#attributes'     => array('onChange' => "update_value_with_other_list($cntr);")
    );

    if (is_array($listvalues) && $listvalues[0] > 0) {
      $res2 = db_query("SELECT id, fieldname FROM {nexlist_fields} WHERE lid=%d", $listvalues[0]);
      $fieldoptions = array(0 => 'Select Field');
      $i = 0;
      while ($B = db_fetch_array($res2)) {
        $fieldoptions[$i++] = $B['fieldname'];
      }
    }
    else {
      $fieldoptions = array(0 => 'Select Field');
    }

    $form['field' . $cntr] = array(
      '#type'           => 'select',
      '#options'        => $fieldoptions,
      '#size'           => 1,
      '#default_value'  => (is_array($listvalues)) ? $listvalues[1]:'',
      '#maxlength'      => 255,
      '#required'       => FALSE,
      '#attributes'     => array('onChange' => "update_value_with_other_list($cntr);")
    );

    $checked = ($A['predefined_function'] == 0) ? '' : 'checked';
    $form['isfunction' . $cntr] = array(
      '#type'           => 'checkbox',
      '#attributes'     => array($checked => ''),
      '#default_value'  => '',
      '#maxlength'      => 255,
      '#required'       => TRUE,
      //'#value'          => '1'
    );
  }

  $form['numberofitems'] = array(
    '#attributes'     => array('style' => "display: none;"),
    '#type'           => 'textfield',
    '#value'          => $cnt,
    '#size'           => 20,
    '#default_value'  => '',
    '#maxlength'      => 255,
    '#required'       => TRUE,
  );

  $form['nexlistid'] = array(
    '#attributes'     => array('style' => "display: none;"),
    '#type'           => 'textfield',
    '#value'          => $nexlist_id,
    '#size'           => 20,
    '#default_value'  => '',
    '#maxlength'      => 255,
    '#required'       => TRUE,
  );

  $form['delid'] = array(
    '#type'           => 'hidden',
    '#value'          => '',
    '#default_value'  => '',
  );

  /**need a way to get new fields in there**/
  $form['addnewfield'] = array(
    '#type'           => 'submit',
    '#value'          => 'Add New Field',
  );

  $form['submit'] = array(
    '#type'           => 'submit',
    '#value'          => 'Save',
  );

  $form['#submit'][] = 'nexlist_add_form_fields_submit';

  return $form;
}

function nexlist_theme_form_add_fields($form) {
  //ok, so we have to now lay out the form in the template
  $output = theme("nexlist_form_add_fields_elements", $form);
  return $output ;
}

function nexlist_add_form_fields_submit($form, &$form_state) {
  //ok, lets cycle over all of the form entry items and update their values!
  if ($form_state['clicked_button']['#value'] == 'Add New Field') {
    db_query("INSERT INTO {nexlist_fields} (lid, fieldname) VALUES (%d, 'New Field')", $form_state['values']['nexlistid']);
  }
  elseif ($form_state['clicked_button']['#value'] == 'X') {
    $delid = intval($form['#post']['delid']);
    db_query("DELETE FROM {nexlist_fields} WHERE id=%d", $delid);
  }
  else {
    for ($cntr = 0; $cntr < $form_state['values']['numberofitems']; $cntr++) {
      $fieldname = db_escape_string($form['#post']['name' . $cntr]);
      $isfunc = intval($form['#post']['isfunction' . $cntr]);
      $sql  = "UPDATE {nexlist_fields} SET ";
      $sql .= "fieldname='{$fieldname}', ";
      $sql .= "value_by_function='{$form['#post']['value' . $cntr]}', ";

      if ($form_state['values']['isfunction' . $cntr] == 1) {
        $sql .="predefined_function=1 ";
      }
      else {
        $sql .="predefined_function=0 ";
      }

      $sql .= "WHERE id={$form_state['values']['id' . $cntr]} ";
      db_query($sql);
    }

    if (!db_error()) {
      drupal_set_message(t($msg . " Your List has been Saved!"));
    }
    else {
      drupal_set_message(t("There has been an error saving your list"));
    }
  }
}

/* end add-form-fields area */


/* the following is for the add values form */
function nexlist_form_add_values($form_state, $nexlist_id=0, $page=0, $edit_id=0) {
  //ok.. we are going to loop through all of the items in the db for this list
  //we will simply show the editable item as the form and the rest will be html output from
  //the preprocessed page
  include('custom.php');

  if ($edit_id != 0) {
    //editing a value
    $res = db_query("SELECT id, lid, itemorder, value, active FROM {nexlist_items} WHERE lid=%d AND id=%d", $nexlist_id, $edit_id);

    $A = db_fetch_array($res);
    $form['id'] = array(
      '#attributes'     => array('readonly' => 'true'),
      '#value'          => $A['id'],
      '#type'           => 'textfield',
      '#size'           => 2,
      '#default_value'  => '',
      '#maxlength'      => 255,
      '#required'       => TRUE,
    );

    $form['itemorder'] = array(
      '#value'          => $A['itemorder'],
      '#type'           => 'textfield',
      '#size'           => 2,
      '#default_value'  => '',
      '#maxlength'      => 255,
      '#required'       => TRUE,
    );

    //now here we are trying to explode out the values stored in the database for this list
    //problem is that we should really be exploding out the values and line them up to the fields
    $fieldsres = db_query("SELECT * FROM {nexlist_fields} WHERE lid=%d ORDER BY id ASC", $nexlist_id);
    $cnt = db_affected_rows();

    $arr = explode(',', $A['value']);
    //alrighty.. the array of exploded values should now mean that we can line up the values to the field list.
    if (is_array($arr)) {
      for ($cntr = 0; $cntr < count($arr); $cntr++) {
        $A = db_fetch_array($fieldsres);
        if ($A['predefined_function'] == 1) {
          if (strpos($A['value_by_function'], '[list:') !== FALSE) {
            $listvaluesstr = drupal_substr($A['value_by_function'], 6);
            $listvaluesstr = str_replace(']', '', $listvaluesstr);
            $listvalues = explode(',', $listvaluesstr);
            $options = nexlist_option_list('alist', '', $listvalues[0], $listvalues[1]);
            $options[''] = 'Select Value';
            //we have to go fetch the function information/drop down here.
            $form['v' . $cntr] = array(
              '#type'           => 'select',
              '#size'           => 1,
              '#default_value'  => $arr[$cntr],
              '#options'        => $options
            );
          }
          else {
            //we have to go fetch the function information/drop down here.
            $form['v' . $cntr] = array(
              '#type' => 'select',
              '#size' => 1,
              '#default_value' => $arr[$cntr],
              '#options' => $A['value_by_function']('edit', $arr[$cntr])
            );
          }
        }
        else {
          $form['v' . $cntr] = array(
            '#value'          => $arr[$cntr],
            '#type'           => 'textfield',
            '#size'           => 10,
            '#default_value'  => '',
            '#maxlength'      => 255,
          );
        }
      }

      if (count($arr) < $cnt) { //missing a field or two
        for ($cntr; $cntr < $cnt; $cntr++) {
          $form['v' . $cntr] = array(
            '#value'          => $arr[$cntr],
            '#type'           => 'textfield',
            '#size'           => 10,
            '#default_value'  => '',
            '#maxlength'      => 255,
          );
        }
      }
    }
    else { //its a singlular value
      $form['v0'] = array(
        '#value'          => $A['value'],
        '#type'           => 'textfield',
        '#size'           => 10,
        '#default_value'  => '',
        '#maxlength'      => 255,
      );
    }

    $form['submit'] = array(
      '#type'             => 'submit',
      '#value'            => 'Save',
    );
  }

    $form['list_id'] = array(
      '#attributes'     => array('readonly' => "true", 'style' => "display:none;"),
      '#value'          => $nexlist_id,
      '#type'           => 'textfield',
      '#size'           => 2,
      '#default_value'  => '',
      '#maxlength'      => 255,
      '#required'       => TRUE,
    );

    $form['nitemorder'] = array(
      '#value'          => '',
      '#type'           => 'textfield',
      '#size'           => 2,
      '#default_value'  => '',
      '#maxlength'      => 255,
    );

    $fieldsres = db_query("SELECT * FROM {nexlist_fields} WHERE lid=%d ORDER BY id ASC", $nexlist_id);
    $cnt = db_affected_rows();

    for ($cntr = 0; $cntr < $cnt; $cntr++) {
      $A = db_fetch_array($fieldsres);
      if ($A['predefined_function'] == 1) {
        if (strpos($A['value_by_function'], '[list:') !== FALSE) {
          $listvaluesstr = drupal_substr($A['value_by_function'], 6);
          $listvaluesstr = str_replace(']', '', $listvaluesstr);
          $listvalues = explode(',', $listvaluesstr);
          $options = nexlist_option_list('alist', '', $listvalues[0], $listvalues[1]);
          $options[''] = 'Select Value';

          $form['n' . $cntr] = array(
            '#type'         => 'select',
            '#size'         => 1,
            '#options'      => $options
          );
        }
        else {
          $form['n' . $cntr] = array(
            '#type'         => 'select',
            '#size'         => 1,
            '#options'      => $A['value_by_function']('edit', '')
          );
        }
      }
      else {
        $form['n' . $cntr] = array(
          '#value'          => '',
          '#type'           => 'textfield',
          '#size'           => 10,
          '#default_value'  => '',
          '#maxlength'      => 255
        );
      }
    }

    $form['submitNewItem'] = array(
      '#type' => 'submit',
      '#value' => 'Add New Item',
    );

    $form['#submit'][] = 'nexlist_add_form_values_submit';

    return $form;
}

function nexlist_theme_form_add_values($form) {
  $formparms = $form['#parameters'];
  $nexlist_id = $formparms[2];
  $page = $formparms[3];
  $edit_id = $formparms[4];

  $res = db_query("SELECT id, lid, itemorder, value, active from {nexlist_items} WHERE lid=%d ORDER BY itemorder ASC", $nexlist_id);
  $fieldsres = db_query("SELECT fieldname,predefined_function,value_by_function FROM {nexlist_fields} WHERE lid=%d", $nexlist_id);
  $fieldarray = array();
  $functionarray = array();

  while ($A = db_fetch_array($fieldsres)) {
    $fieldarray[] = $A['fieldname'];
    if ($A['predefined_function'] == 1) {
      $functionarray[] = array(1, $A['value_by_function']);
    }
    else {
      $functionarray[] = array(0, '');
    }
  }

  $output = theme("nexlist_form_add_values_elements", $form, $res, $edit_id, $fieldarray, $nexlist_id, $page, $functionarray);

  return $output ;
}

function nexlist_add_form_values_submit($form, &$form_state) {
  $fieldsres = db_query("SELECT fieldname FROM {nexlist_fields} WHERE lid=%d", $form_state['values']['list_id']);
  $cnt = db_affected_rows();

  if ($form_state['clicked_button']['#value'] == 'Add New Item') {
      $val='';
      for ($cntr = 0; $cntr < $cnt; $cntr++) {
        if ($val != '') $val .= ',';
        $val .= $form['#post']['n' . $cntr];
      }

      if ($form['#post']['nitemorder'] == '') {
        $res = db_query("SELECT MAX(itemorder) as cnt FROM {nexlist_items} WHERE lid=%d", $form['#post']['list_id']);
        $A = db_fetch_array($res);
        $max = intval($A['cnt']);
        if ($max == 0) {
          $max = 10;
        }
        else {
          $max += 10;
        }
      }
      else{
        $max = $form['#post']['nitemorder'];
      }

      db_query("INSERT INTO {nexlist_items} (lid, itemorder, value) VALUES (%d, %d, '%s')", $form['#post']['list_id'], $max, $val);
  }
  else {
    $id = $form['#post']['id'];
    $itemorder = $form['#post']['itemorder'];
    $val = '';

    for ($cntr = 0; $cntr < $cnt; $cntr++) {
      if ($val != '') $val .= ',';
      $val .= $form['#post']['v' . $cntr];
    }

    db_query("UPDATE {nexlist_items} SET value='%s', itemorder=%d WHERE id=%d", $val, $itemorder, $id);
  }
}
/* end the add values form area*/
